<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { 
  getAppVoById, 
  updateApp, 
  updateAppByAdmin,
  getAppVoByIdByAdmin,
  uploadAppCover
} from '@/api/appController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { SaveOutlined, ArrowLeftOutlined, UploadOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { getCodeGenTypeName } from '@/constants/codeGenType'

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

// 页面状态
const loading = ref(false)
const saveLoading = ref(false)
const isAdmin = ref(false)
const coverUploading = ref(false)

// 表单数据
const formData = reactive<{
  id?: number
  appName?: string
  cover?: string
  priority?: number
  tags?: string[]
}>({})

// 原始应用数据
const originalApp = ref<API.AppVO>({})

// 默认标签选项
const defaultTags = [
  // 应用类型
  '网站', '工具', '游戏', '教育', '商务', '博客', '电商', '社交',
  // 技术栈
  'HTML', 'CSS', 'JavaScript', 'Vue', 'React', 'TypeScript',
  // 风格
  '简约', '现代', '创意', '专业', '可爱', '商务风',
  // 功能
  '管理系统', 'Landing Page', '移动端', '响应式', '交互式'
]

// 表单验证规则
const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 1, max: 50, message: '应用名称长度应在1-50个字符之间', trigger: 'blur' },
  ],
  cover: [
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' },
  ],
  priority: [
    { type: 'number', min: 0, max: 99, message: '优先级范围为0-99', trigger: 'blur' },
  ],
}

/**
 * 获取应用详情
 */
const fetchAppDetail = async (retryCount = 0) => {
  const appId = route.params.id as string
  if (!appId) {
    message.error('应用ID不存在')
    router.push('/')
    return
  }

  // 只在第一次请求时显示loading
  if (retryCount === 0) {
    loading.value = true
  }

  try {
    // 判断是否为管理员
    isAdmin.value = loginUserStore.loginUser.userRole === 'admin'
    
    // 直接使用字符串ID，避免精度丢失
    const appIdString = String(appId)
    
    console.log('应用编辑页面 ID 处理:')
    console.log('- 原始 appId:', appId)
    console.log('- 字符串 appId:', appIdString)
    
    // 根据权限调用不同的接口
    const res = isAdmin.value 
      ? await getAppVoByIdByAdmin({ id: appIdString })
      : await getAppVoById({ id: appIdString })

    if (res.data.code === 0 && res.data.data) {
      originalApp.value = res.data.data
      
      // 检查权限：普通用户只能编辑自己的应用
      if (!isAdmin.value && res.data.data.userId !== loginUserStore.loginUser.id) {
        loading.value = false
        message.error('您没有权限编辑此应用')
        router.push('/')
        return
      }

      // 填充表单数据
      formData.id = res.data.data.id
      formData.appName = res.data.data.appName
      formData.cover = res.data.data.cover
      formData.priority = res.data.data.priority
      formData.tags = res.data.data.tags || []
      
      loading.value = false
      return
    } else {
      // 如果是数据不存在且重试次数少于5次，则等待后重试
      if (res.data.message?.includes('请求数据不存在') && retryCount < 5) {
        console.log(`应用编辑数据暂未同步，正在重试... (${retryCount + 1}/5)`)
        setTimeout(() => {
          fetchAppDetail(retryCount + 1)
        }, 2000)
        return
      }
      
      loading.value = false
      message.error('应用不存在或已被删除')
      router.push('/')
    }
  } catch (error) {
    // 网络错误也进行重试
    if (retryCount < 5) {
      console.log(`网络请求失败，正在重试... (${retryCount + 1}/5)`)
      setTimeout(() => {
        fetchAppDetail(retryCount + 1)
      }, 2000)
      return
    }
    
    loading.value = false
    message.error('网络连接失败，请检查网络')
    router.push('/')
  }
}

/**
 * 保存应用信息
 */
const handleSave = async () => {
  if (!formData.id) return

  saveLoading.value = true
  try {
    let res
    
    if (isAdmin.value) {
      // 管理员可以更新所有字段
      res = await updateAppByAdmin({
        id: formData.id,
        appName: formData.appName,
        cover: formData.cover,
        priority: formData.priority,
        tags: formData.tags,
      })
    } else {
      // 普通用户可以更新应用名称、标签和封面
      res = await updateApp({
        id: formData.id,
        appName: formData.appName,
        cover: formData.cover,
        tags: formData.tags,
      })
    }

    if (res.data.code === 0) {
      message.success('保存成功')
      // 可以选择返回上一页或刷新当前页面
      router.back()
    } else {
      message.error('保存失败：' + res.data.message)
    }
  } catch (error) {
    message.error('保存失败，请检查网络连接')
  } finally {
    saveLoading.value = false
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.back()
}

/**
 * 预览封面图片
 */
const previewCover = (url?: string) => {
  if (!url) return false
  
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

/**
 * 处理封面上传
 */
const handleCoverUpload = async (file: File) => {
  if (!formData.id) {
    message.error('应用ID不存在')
    return false
  }

  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }

  // 验证文件大小 (10MB)
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB！')
    return false
  }

  coverUploading.value = true
  
  try {
    const res = await uploadAppCover(file, formData.id)
    if (res.data.code === 0 && res.data.data) {
      formData.cover = res.data.data
      message.success('封面上传成功')
      return true
    } else {
      message.error('封面上传失败：' + res.data.message)
      return false
    }
  } catch (error) {
    message.error('封面上传失败，请检查网络连接')
    return false
  } finally {
    coverUploading.value = false
  }
}

/**
 * 封面上传前的处理
 */
const beforeCoverUpload = (file: File) => {
  handleCoverUpload(file)
  return false // 阻止自动上传
}

// 页面加载时获取应用详情
onMounted(() => {
  fetchAppDetail()
})
</script>

<template>
  <div class="app-edit-page">
    <a-card class="edit-card" :loading="loading">
      <!-- 页面标题 -->
      <template #title>
        <div class="page-header">
          <a-button type="text" @click="goBack" class="back-button">
            <template #icon><ArrowLeftOutlined /></template>
            返回
          </a-button>
          <span class="page-title">编辑应用</span>
        </div>
      </template>

      <template #extra>
        <a-button 
          type="primary" 
          :loading="saveLoading"
          @click="handleSave"
        >
          <template #icon><SaveOutlined /></template>
          保存
        </a-button>
      </template>

      <!-- 编辑表单 -->
      <a-form
        :model="formData"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        class="edit-form"
      >
        <!-- 应用ID（只读） -->
        <a-form-item label="应用ID">
          <a-input :value="formData.id" disabled />
        </a-form-item>

        <!-- 应用名称 -->
        <a-form-item label="应用名称" name="appName">
          <a-input 
            v-model:value="formData.appName" 
            placeholder="请输入应用名称"
            :maxlength="50"
            show-count
          />
        </a-form-item>

        <!-- 应用标签 -->
        <a-form-item label="应用标签" name="tags">
          <a-select
            v-model:value="formData.tags"
            mode="tags"
            style="width: 100%"
            placeholder="选择或输入自定义标签，最多5个"
            :options="defaultTags.map(tag => ({ label: tag, value: tag }))"
            :max-tag-count="5"
            :allow-clear="true"
          />
          <div class="form-help">
            标签可以帮助用户更好地找到和了解您的应用
          </div>
        </a-form-item>

        <!-- 应用封面 -->
        <a-form-item label="应用封面" name="cover">
          <div class="cover-upload-container">
            <!-- 上传组件 -->
            <a-upload
              name="cover"
              list-type="picture-card"
              class="cover-uploader"
              :show-upload-list="false"
              :before-upload="beforeCoverUpload"
              accept="image/*"
            >
              <div class="upload-area">
                <a-spin v-if="coverUploading" />
                <template v-else>
                  <div v-if="formData.cover" class="cover-preview">
                    <img :src="formData.cover" alt="封面预览" class="preview-image" />
                    <div class="upload-overlay">
                      <UploadOutlined />
                      <div class="upload-text">重新上传</div>
                    </div>
                  </div>
                  <div v-else class="upload-placeholder">
                    <PlusOutlined />
                    <div class="upload-text">点击上传封面</div>
                  </div>
                </template>
              </div>
            </a-upload>
            
            <!-- 管理员可以手动输入URL -->
            <div v-if="isAdmin" class="cover-url-input">
              <a-input 
                v-model:value="formData.cover" 
                placeholder="或输入封面图片URL"
                addon-before="URL"
              />
            </div>
          </div>
          
          <div class="form-help">
            <div class="help-section">
              <p><strong>上传要求：</strong></p>
              <p>• 支持 JPG、JPEG、PNG、GIF 格式</p>
              <p>• 图片大小不超过 10MB</p>
              <p>• 建议尺寸 400x300 像素</p>
            </div>
            
            <div class="help-section auto-cover-tip">
              <p><strong>自动封面说明：</strong></p>
              <p v-if="!formData.cover">• 如不手动上传封面，部署完成后会自动生成应用截图作为封面</p>
              <p v-else>• 已设置自定义封面，部署时不会覆盖当前封面</p>
              <p>• 部署后可随时重新上传封面进行替换</p>
              <p>• 自动截图会在应用成功部署并可访问后生成</p>
            </div>
          </div>
        </a-form-item>

        <!-- 优先级（仅管理员可编辑） -->
        <a-form-item v-if="isAdmin" label="优先级" name="priority">
          <a-input-number 
            v-model:value="formData.priority" 
            :min="0" 
            :max="99"
            placeholder="0-99，99为精选应用"
            style="width: 200px"
          />
          <div class="form-help">
            设置为 99 将显示为精选应用
          </div>
        </a-form-item>

        <!-- 应用信息（只读） -->
        <a-divider>应用信息</a-divider>

        <a-form-item label="生成类型">
          <a-tag :color="getTypeColor(originalApp.codeGenType)">
            {{ getCodeGenTypeName(originalApp.codeGenType || '') }}
          </a-tag>
        </a-form-item>

        <a-form-item label="创建者">
          <div class="creator-info">
            <a-avatar :src="originalApp.user?.userAvatar" :size="32">
              {{ originalApp.user?.userName?.charAt(0) }}
            </a-avatar>
            <div class="creator-details">
              <div class="creator-name">{{ originalApp.user?.userName || '未知用户' }}</div>
              <div class="creator-account">{{ originalApp.user?.userAccount }}</div>
            </div>
          </div>
        </a-form-item>

        <a-form-item label="部署状态">
          <a-tag v-if="originalApp.deployKey" color="green">
            已部署
          </a-tag>
          <a-tag v-else color="default">
            未部署
          </a-tag>
          <span v-if="originalApp.deployedTime" class="deploy-time">
            部署时间：{{ new Date(originalApp.deployedTime).toLocaleString() }}
          </span>
        </a-form-item>

        <a-form-item label="创建时间">
          {{ originalApp.createTime ? new Date(originalApp.createTime).toLocaleString() : '-' }}
        </a-form-item>

        <a-form-item label="更新时间">
          {{ originalApp.updateTime ? new Date(originalApp.updateTime).toLocaleString() : '-' }}
        </a-form-item>

        <!-- 初始提示词（只读） -->
        <a-form-item label="初始提示词">
          <a-textarea 
            :value="originalApp.initPrompt" 
            :rows="4"
            disabled
            placeholder="无初始提示词"
          />
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <a-space>
          <a-button @click="goBack">
            取消
          </a-button>
          <a-button 
            type="primary" 
            :loading="saveLoading"
            @click="handleSave"
          >
            <template #icon><SaveOutlined /></template>
            保存
          </a-button>
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts">
/**
 * 根据生成类型获取对应的颜色
 */
const getTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    html: 'orange',
    multi_file: 'blue',
  }
  return colorMap[type?.toLowerCase() || ''] || 'default'
}
</script>

<style scoped>
.app-edit-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.edit-card {
  box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16),
              0 3px 6px 0 rgba(0, 0, 0, 0.12),
              0 5px 12px 4px rgba(0, 0, 0, 0.09);
  border-radius: 8px;
}

/* 页面头部 */
.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-button {
  padding: 0;
  color: #1890ff;
}

.back-button:hover {
  background: rgba(24, 144, 255, 0.1);
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

/* 表单样式 */
.edit-form {
  margin-top: 24px;
}

:deep(.ant-form-item-label) {
  font-weight: 600;
}

/* 封面上传容器 */
.cover-upload-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cover-uploader {
  display: inline-block;
}

.upload-area {
  width: 200px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fafafa;
  overflow: hidden;
  position: relative;
}

.upload-area:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.upload-placeholder .anticon {
  font-size: 32px;
  margin-bottom: 8px;
  color: #999;
}

.upload-text {
  font-size: 14px;
  text-align: center;
  color: #666;
}

.cover-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  border-radius: 6px;
}

.cover-preview:hover .upload-overlay {
  opacity: 1;
}

.upload-overlay .anticon {
  font-size: 24px;
  margin-bottom: 4px;
}

.upload-overlay .upload-text {
  font-size: 12px;
  color: white;
}

.cover-url-input {
  margin-top: 8px;
}

/* 覆盖 ant-design-vue 的默认样式 */
:deep(.cover-uploader .ant-upload.ant-upload-select-picture-card) {
  width: 200px;
  height: 150px;
  border: none;
  background: transparent;
}

:deep(.cover-uploader .ant-upload.ant-upload-select-picture-card:hover) {
  border: none;
}

/* 表单帮助文本 */
.form-help {
  margin-top: 4px;
  font-size: 12px;
  color: #8c8c8c;
}

.help-section {
  margin-bottom: 12px;
}

.help-section:last-child {
  margin-bottom: 0;
}

.help-section p {
  margin: 4px 0;
}

.help-section strong {
  color: #333;
  font-weight: 600;
}

.auto-cover-tip {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
  padding: 8px 12px;
  margin-top: 8px;
}

.auto-cover-tip p {
  margin: 3px 0;
}

.auto-cover-tip strong {
  color: #52c41a;
}

/* 创建者信息 */
.creator-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.creator-details {
  display: flex;
  flex-direction: column;
}

.creator-name {
  font-weight: 500;
  color: #262626;
}

.creator-account {
  font-size: 12px;
  color: #8c8c8c;
}

/* 部署时间 */
.deploy-time {
  margin-left: 12px;
  font-size: 12px;
  color: #8c8c8c;
}

/* 操作按钮 */
.form-actions {
  margin-top: 32px;
  text-align: center;
  padding-top: 24px;
  border-top: 1px solid #e8e8e8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-edit-page {
    margin: 0;
  }

  :deep(.ant-form-item-label) {
    text-align: left;
  }

  :deep(.ant-col-4) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  :deep(.ant-col-16) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .cover-input-group {
    flex-direction: row;
    align-items: flex-start;
  }

  .cover-input {
    flex: 1;
  }

  .cover-preview {
    flex-shrink: 0;
    width: 80px;
    height: 60px;
  }
}
</style>
